package de.tum.activities.Login;


import org.xmlrpc.android.XMLRPCException;

import de.tum.ExamApp.R;
import de.tum.Misc.ToastFromThread;
import de.tum.activities.ExamApp.ExamAppActivity;
import de.tum.control.Synchronizer;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

/**
 * starting activity of the app.
 * 
 * it is providing two EditTexts for username and password.
 * he can try to login with the button.
 * 
 *  login data is send to server and checked -> if true -> direct to the ExamOverview
 *
 * 
 * @author Rupert
 *
 */
public class LoginActivity extends Activity implements OnClickListener   {
	
	private EditText username, password;
	private Button loginButton;
	
	private ProgressDialog progressDialog;
	
	private Context context;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        
        context = getApplicationContext();
        
        username = (EditText) findViewById(R.id.login_name);
        password = (EditText) findViewById(R.id.login_password);
        
        loginButton = (Button) findViewById(R.id.login_button);
        loginButton.setOnClickListener(this);
    }

	public void onClick(View view) {
		int id =view.getId();
		
		if(id == R.id.login_button){
				tryLogin();
		}else{
			
		}

		
	}

	/**
	 * the login verfication
	 */
	private void tryLogin() {
	
		/**
		 * progress dialog is shown to avoid ANR and for better usability
		 */
		progressDialog = ProgressDialog.show(LoginActivity.this, "Server-Connection", "Login to server...");
		
		
		/**
		 * using a thread for background action -> login
		 */
		new Thread() {

			public void run() {
				
				int userId = -1;
				ToastFromThread loginIncorrect = new ToastFromThread(getString(R.string.login_incorrect), getApplicationContext());
				ToastFromThread connectionFailed = new ToastFromThread(getString(R.string.connection_failed), getApplicationContext());
				
				try{
					/**
					 * Login data is send to server and checked
					 * if correct userId is set -> userId is higher or equal than 0
					 */
					String usernameString = username.getText().toString();
					String passwordString = password.getText().toString();
					Log.d("Login", "User: "+usernameString+" / Passwort: "+passwordString);
					
					Synchronizer sync = new Synchronizer();
					userId = sync.checkLoginData(usernameString, passwordString);
					Log.d("Login", ""+userId);
	
				} catch (XMLRPCException e) {
					Log.d("RESULT", "EXCEPTION");
					runOnUiThread(connectionFailed);
					progressDialog.dismiss();
	
				}
	
				// login correct?
				if(userId >= 0){
					
					// save login data
					SharedPreferences localSharedPreferences = PreferenceManager
							.getDefaultSharedPreferences(context);
					Editor e = localSharedPreferences.edit();
		
					e.putString("username", username.getText().toString());
					e.putString("password", password.getText().toString());
					e.putInt("userId", userId);
		
					e.commit();
					
					// dismiss the progress dialog
					progressDialog.dismiss();
					Intent mainMenuActivity = new Intent(LoginActivity.this, ExamAppActivity.class);
					startActivity(mainMenuActivity);
				}else{
					runOnUiThread(loginIncorrect);
				}
				progressDialog.dismiss();
					
			}

		}.start();
		
	}
}
